package com.jago.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 判断上传的是普通表单还是带文件的表单
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;     // 不处理普通表单
        }

        System.out.println("处理文件");
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);

        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        // 缓存、临时文件
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File file = new File(tmpPath);

        if (!file.exists()) {
            file.mkdir();
        }

        // 1、创建DiskFileItemFactory对象，处理文件上传路径或者大小限制
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 缓冲区大小为1M
        factory.setSizeThreshold(1024 * 1024);
        factory.setRepository(file);

        // 2、获取ServletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 监听文件上传进度
        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("总大小：" + pContentLength + "已上传：" + pBytesRead);
            }
        });

        // 处理乱码问题
        upload.setHeaderEncoding("utf-8");
        // 设置单个文件的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        // 设置总共能够上传文件的大小
        upload.setSizeMax(1024 * 1024 * 10);

        // 3、处理上传的文件
        // 把前端请求解析，封装成一个FileItem对象，需要从ServletFileUpload对象中获取
        List<FileItem> fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        for (FileItem fileItem : fileItems) {
            // 判断上传的文件是普通的表单还是带文件的表单
            if (fileItem.isFormField()) {
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");// 处理乱码
                System.out.println(name + "：" + value);
            } else {
                // 处理文件
                String uploadFileName = fileItem.getName();
                // 处理不合法的文件名
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }
                // 获得上传的文件名
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                // 获得文件的后缀名
                String fileTxtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                // 存放地址
                String uuidPath = UUID.randomUUID().toString();
                String realPath = uploadPath + "/" + uuidPath;
                File realPathFile = new File(realPath);
                if (!realPathFile.exists()) {
                    realPathFile.mkdir();
                }

                // 文件传输
                InputStream inputStream = fileItem.getInputStream();
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
                inputStream.close();
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
